use core::{cell::UnsafeCell, ptr::null_mut};

use crate::{
    c::rtx_os::{
        osMutexAcquire, osMutexAttr_t, osMutexId_t, osMutexNew, osMutexPrioInherit,
        osMutexRecursive, osMutexRelease, osMutexRobust, osRtxMutex_t, osWaitForever,
    },
    utils::AlignStore,
};

const CB_SIZE: usize = size_of::<osRtxMutex_t>();

unsafe impl Send for Mutex {}
unsafe impl Sync for Mutex {}

pub struct Mutex {
    cb_mem: AlignStore<CB_SIZE>,
    id: UnsafeCell<osMutexId_t>,
}

impl Mutex {

    pub const fn const_new() -> Self {
        Self {
            cb_mem: AlignStore::const_new(),
            id: UnsafeCell::new(null_mut())
        }
    }

    pub unsafe fn create(&self, name: &str) {
        let attr = osMutexAttr_t {
            name: name.as_ptr() as *const i8,
            attr_bits: osMutexPrioInherit | osMutexRecursive | osMutexRobust,
            cb_mem: self.cb_mem.raw_ptr(),
            cb_size: CB_SIZE as u32,
        };
        let id = osMutexNew(&attr);
        #[cfg(feature = "assert")]
        assert!(id != null_mut(), "mutex create fail");
        *self.id.get() = id;
    }

    pub unsafe fn unsafe_lock(&self) -> i32 {
        osMutexAcquire(*self.id.get(), osWaitForever)
    }

    pub unsafe fn unsafe_unlock(&self) -> i32 {
        osMutexRelease(*self.id.get())
    }
}
